// import { stringObjectDTO } from './dto'
import { ElMessageBox, MessageBoxData } from 'element-plus'
import dayjs from 'dayjs'
// import { FormItemDto, AnyObject } from '@/components/form-component/index.vue'
import { VNode } from 'vue'
import { FormDataDto, FormItemDto } from '@/components/form-component/type'
import { AnyObject } from '@/api/type'
/**
 * 时间格式化
 */
export function dateFormat(fmt: string, date: Date): string {
    let ret
    const opt: any = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    }
    for (const k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
            fmt = fmt.replace(
                ret[1],
                ret[1].length === 1
                    ? opt[k]
                    : opt[k].padStart(ret[1].length, '0')
            )
        }
    }
    return fmt
}

/**
 * 阻塞等待
 */
export function wait(timeout = 1000): Promise<undefined> {
    return new Promise(resolve => {
        setTimeout(resolve, timeout)
    })
}

/**
 * 节流
 */
function Shake() {
    let timer: any = -1
    return function (obj: () => any, millisecond = 500) {
        clearTimeout(timer)
        timer = setTimeout(obj, millisecond)
    }
}
export const shake = Shake()

// 确认窗
export function confirm(title: string, desc: string | VNode): Promise<MessageBoxData> {
    return ElMessageBox.confirm(desc, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    })
}

// 输入窗
export function prompt(title: string, desc: string): Promise<MessageBoxData> {
    return ElMessageBox.prompt(desc, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    })
}

export function closewin(): void {
    setTimeout(() => {
        if (
            navigator.userAgent.indexOf('Firefox') !== -1 ||
            navigator.userAgent.indexOf('Chrome') !== -1
        ) {
            window.location.href = 'about:blank'
            window.close()
        } else {
            window.opener = null
            window.open('', '_self')
            window.close()
        }
    }, 5000)
}
// 身份证转年龄
export function getCardAge(identityCard: string) {
    const len = (identityCard + '').length
    if (len === 0) {
        return 0
    } else {
        if ((len !== 15) && (len !== 18)) { // 身份证号码只能为15位或18位其它不合法
            return 0
        }
    }
    let strBirthday = ''
    if (len === 18) { // 处理18位的身份证号码从号码中得到生日和性别代码
        strBirthday = identityCard.substr(6, 4) + '/' + identityCard.substr(10, 2) + '/' + identityCard.substr(12, 2)
    }
    if (len === 15) {
        strBirthday = '19' + identityCard.substr(6, 2) + '/' + identityCard.substr(8, 2) + '/' + identityCard.substr(10, 2)
    }
    console.log(strBirthday, 'strBirthday')
    // 时间字符串里，必须是“/”
    const birthDate = new Date(strBirthday)
    console.log(birthDate, 'birthDate')
    const nowDateTime = new Date()
    let age = nowDateTime.getFullYear() - birthDate.getFullYear()
    // 再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
    if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() === birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
        age--
    }
    return age
}
export interface FormTestingErroeDto {
    richText: {
        text: string
    },
}
export interface FormTestingDto {
    userName: string | FormTestingErroeDto[],
    idCardNo: string | FormTestingErroeDto[],
    serveCompanyName: null,
    joinType: number
}
// 表格校验
export function formTesting(name: string | FormTestingErroeDto[], idCode: string | FormTestingErroeDto[]) {
    console.log(name, '校验名称')
    console.log(idCode, 'code名称')
    let text = ''
    let code = ''
    if (typeof (name) === 'object' || typeof (idCode) === 'object') {
        if (typeof (name) === 'object' && typeof (idCode) === 'string') {
            (name as any).richText.forEach((item: { text: string }) => {
                text = text += item.text
            })
            code = (idCode as string)
        }
        if (typeof (idCode) === 'object' && typeof (name) === 'string') {
            (idCode as any).richText.forEach((item: { text: string }) => {
                code = code += item.text
            })
            text = (name as string)
        }
        if (typeof (idCode) === 'object' && typeof (name) === 'object') {
            (idCode as any).richText.forEach((item: { text: string }) => {
                code = code += item.text
            });
            (name as any).richText.forEach((item: { text: string }) => {
                text = text += item.text
            })
        }
        // console.log((item.getCell(1).value as any).richText, 'item.getCell(1).value')
        // (item.getCell(1).value as any).richText
        return {
            name: text,
            code: code
        }
    }
    return {
        name: '',
        code: ''
    }
}
export default {
    prompt,
    confirm
}
// 中国标准时间 获取年月日
export function GetDate(date: any) {
    const year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    month = month >= 10 ? month : '0' + month
    day = day >= 10 ? day : '0' + day
    return year + '-' + month + '-' + day
}
// 中国标准时间 转 年-月-日 时：分：秒 =》new Date(时间搓)=>中国标准时间
export function GetDateTime(date: any) {
    const year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    let hour = date.getHours()
    let min = date.getMinutes()
    let sec = date.getSeconds()
    month = month >= 10 ? month : '0' + month
    day = day >= 10 ? day : '0' + day
    hour = hour >= 10 ? hour : '0' + hour
    min = min >= 10 ? min : '0' + min
    sec = sec >= 10 ? sec : '0' + sec
    return year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + sec
}

export function convertCurrency(money: any) {
    //汉字的数字
    const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
    //基本单位
    const cnIntRadice = ['', '拾', '佰', '仟']
    //对应整数部分扩展单位
    const cnIntUnits = ['', '万', '亿', '兆']
    //对应小数部分单位
    const cnDecUnits = ['角', '分', '毫', '厘']
    //整数金额时后面跟的字符
    const cnInteger = '整'
    //整型完以后的单位
    const cnIntLast = '元'
    //最大处理的数字
    // eslint-disable-next-line @typescript-eslint/no-loss-of-precision
    const maxNum = 999999999999999.9999
    //金额整数部分
    let integerNum
    //金额小数部分
    let decimalNum
    //输出的中文金额字符串
    let chineseStr = ''
    //分离金额后用的数组，预定义
    let parts
    // 传入的参数为空情况 
    if (money == '') {
        return ''
    }
    money = parseFloat(money)
    if (money >= maxNum) {
        return ''
    }
    // 传入的参数为0情况 
    if (money == 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger
        return chineseStr
    }
    // 转为字符串
    money = money.toString()
    // indexOf 检测某字符在字符串中首次出现的位置 返回索引值（从0 开始） -1 代表无
    if (money.indexOf('.') == -1) {
        integerNum = money
        decimalNum = ''
    } else {
        parts = money.split('.')
        integerNum = parts[0]
        decimalNum = parts[1].substr(0, 4)
    }
    //转换整数部分
    if (parseInt(integerNum, 10) > 0) {
        let zeroCount = 0
        const IntLen = integerNum.length
        for (let i = 0; i < IntLen; i++) {
            const n = integerNum.substr(i, 1)
            const p = IntLen - i - 1
            const q = p / 4
            const m = p % 4
            if (n == '0') {
                zeroCount++
            } else {
                if (zeroCount > 0) {
                    chineseStr += cnNums[0]
                }
                zeroCount = 0
                chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
            }
            if (m == 0 && zeroCount < 4) {
                chineseStr += cnIntUnits[q]
            }
        }
        // 最后+ 元
        chineseStr += cnIntLast
    }
    // 转换小数部分
    if (decimalNum != '') {
        const decLen = decimalNum.length
        for (let i = 0; i < decLen; i++) {
            const n = decimalNum.substr(i, 1)
            if (n != '0') {
                chineseStr += cnNums[Number(n)] + cnDecUnits[i]
            }
        }
    }
    if (chineseStr == '') {
        chineseStr += cnNums[0] + cnIntLast + cnInteger
    } else if (decimalNum == '') {
        chineseStr += cnInteger
    }

    return chineseStr
}


/**
 * 通过url下载文件并对下载的文件更名
 * @param {*} url 
 * @param {*} filename 
 */
export const downloadFile = (url: any, filename: any) => {
    function getBlob(url: string | URL) {
        return new Promise(resolve => {
            const XML = new XMLHttpRequest()
            XML.open('GET', url, true)
            XML.responseType = 'blob'
            XML.onload = () => {
                if (XML.status === 200) {
                    resolve(XML.response)
                }
            }
            XML.send()
        })
    }
    //下载文件
    function saveAs(blob: any, filename: string) {
        const elelink = document.createElement('a')
        elelink.style.display = 'none'
        elelink.download = filename
        elelink.href = window.URL.createObjectURL(blob)
        document.body.appendChild(elelink)
        elelink.click()
        document.body.removeChild(elelink)
    }
    // 调用以上方法进行下载
    getBlob(url).then(blob => {
        saveAs(blob, filename)
    })
}

export function formatCurrency(amount: number | string, currencySymbol = '', decimalPlaces = 0) {
    // 确保输入是数值类型
    amount = Number(amount)

    // 格式化小数部分
    let formattedAmount = amount.toFixed(decimalPlaces)

    // 添加千位分隔符
    formattedAmount = formattedAmount.replace(/\B(?=(\d{3})+(?!\d))/g, ',')

    // 添加货币符号
    formattedAmount = `${currencySymbol}${formattedAmount}`

    return formattedAmount
}

// 判断是否为整月  
// 检查月份是否相同，且起始日期是1号，结束日期是该月的最后一天  
// 注意：这里简单假设结束日期是该月的最后一天，实际中可能需要更复杂的逻辑来确定最后一天  
export function isFullMonth(startDatevalue: string, endDatevalue: string) {
    const startDate = dayjs(startDatevalue)
    const endDate = dayjs(endDatevalue)
    const startMonth = startDate.month()
    const startDay = startDate.date()
    const endMonth = endDate.month()
    const endDay = endDate.date()
    if (startMonth !== endMonth) return false // 月份不同，显然不是整月  
    if (startDay !== 1) return false // 起始日期不是1号  
    // 检查结束日期是否是该月的最后一天  
    // 可以通过计算下个月的第一天然后减去一天来得到当前月的最后一天  
    const nextMonthFirstDay = endDate.add(1, 'month').startOf('month')
    const lastDayOfMonth = nextMonthFirstDay.subtract(1, 'day')
    return lastDayOfMonth.isSame(endDate, 'day') // 比较结束日期和计算出的最后一天是否相同  
}



/**  
 * 判断给定时间段是否为整年  
 * @param {string|dayjs.Dayjs} startDate 开始日期（字符串或dayjs对象）
 * @param {string|dayjs.Dayjs} endDate 结束日期（字符串或dayjs对象）
 * @returns {boolean} 是否为整年  
 */
export function isFullYear(startDate: string, endDate: string) {
    // 确保startDate和endDate是dayjs对象  
    const start = dayjs(startDate)
    const end = dayjs(endDate)
    // 提取年份  
    const startYear = start.year()
    const endYear = end.year()
    // 严格检查结束日期是否为那一年的最后一天，可以取消注释以下代码  
    const lastDayOfYear = start.endOf('year')
    console.log(start, end, startYear, endYear, lastDayOfYear, 'hsuguyshuy')
    if (endYear !== startYear || !end.isSame(lastDayOfYear, 'day')) {
        return false
    } else {
        return true
    }
    // return startYear === endYear
}

// 一维数组转多维数组
export function convertToOneDimensional(array: Array<any>, subArraySize: number) {
    const twoDimensionalArray = []
    for (let i = 0; i < array.length; i += subArraySize) {
        twoDimensionalArray.push(array.slice(i, i + subArraySize))
    }
    return twoDimensionalArray
}

// 筛选组件筛选条件抽离
export function createQuery(listData: Array<any> | { [key: string]: any }) {
    const query: Record<string, any> = {}
    if (Array.isArray(listData)) {
        for (const item of listData) {
            if (typeof item === 'object' && item !== null && 'prop' in item && 'value' in item) {
                if (item.type === 'date' && item.dateType === 'daterange') {
                    query[item?.propAttrs?.start || item.prop + 'Start'] = Array.isArray(item.value) && item.value.length ? item.value[0] : ''
                    query[item?.propAttrs?.end || item.prop + 'End'] = Array.isArray(item.value) && item.value.length ? item.value[1] : ''
                } else {
                    query[item.prop] = item.value ?? ''
                }
            }
        }
    } else if (typeof listData === 'object' && listData !== null) {
        for (const key in listData) {
            if (Object.hasOwnProperty.call(listData, key) && typeof listData[key] === 'object' && listData[key] !== null && 'prop' in listData[key] && 'value' in listData[key]) {
                const cur = listData[key]
                if (cur.type === 'date' && cur.dateType === 'daterange') {
                    query[cur?.propAttrs?.start || cur.prop + 'Start'] = Array.isArray(cur.value) && cur.value.length ? cur.value[0] : ''
                    query[cur?.propAttrs?.end || cur.prop + 'End'] = Array.isArray(cur.value) && cur.value.length ? cur.value[1] : ''
                } else {
                    query[cur.prop] = cur.value ?? ''
                }
            }
        }
    }
    return query
}


/**
 * @description 创建表单值
 * @param form 表单数据对象
 * @returns 返回创建的表单值对象
 */
export function createFormValue(form: FormDataDto) {
    const model = {} as AnyObject
    Object.values(form.list).forEach((i: FormItemDto) => {
        model[i.prop] = i.defaultValue ?? ''
        if (i.type === 'inputGroup') {
            if (i.extra?.prepend) {
                model[i.extra.prepend.prop] = i.extra.prepend.defaultValue ?? ''
            }
            if (i.extra?.append) {
                model[i.extra.append.prop] = i.extra.append.defaultValue ?? ''
            }
        }
    })
    console.log(666, model)
    return model
}

/**
 * 获取filter的值
 */
export function getFilterDataValue(filterData: AnyObject) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const value = {} as Record<string, any>
    for (const key in filterData.list) {
        value[filterData.list[key].prop] = filterData.list[key].value
    }
    return value
}

/**
 * @description 初始化表单值
 * @param obj 表单对象
 * @param defaultValue 默认值对象
 */
export function initFormValue(obj: AnyObject, defaultValue: AnyObject) {
    for (const key in obj) {
        obj[key] = defaultValue[key] ?? null
    }
}
/**
 * @description 获取查询表单的值
 * @param filterData 
 * @returns 
 */
export function getFormDataValue(formData: FormDataDto) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const value = {} as Record<string, any>
    for (const key in formData.list) {
        value[formData.list[key].prop] = formData.list[key].value
    }
    return value
}

export function setFormDataValue(formData: FormDataDto, value: AnyObject) {
    for (const key in formData.list) {
        formData.list[key].value = value[formData.list[key].prop] ?? ''
    }
}

